﻿using System;
using System.Web;
using Facebook.Api;
using System.Collections.Generic;

namespace Facebook.Web
{
    [Serializable]
    public partial class FacebookWebContext
    {
        public static void Init(HttpContext context)
        {
            FacebookWebRequest.Init(context);
            FacebookWebSession.Init(context);
        }

        public static FacebookWebContext Current
        {
            get
            {
                if (FacebookWebSession.Current["__FBCONTEXT"] == null)
                {
                    try
                    {
                        var config = Configuration.FacebookSection.Current.Applications.GetDefault();
                        FacebookWebSession.Current["__FBCONTEXT"] = new FacebookWebContext(config.ApiKey, config.Secret);
                    }
                    catch (Exception ex)
                    {
                        throw new ApplicationException("An attempt to initialize FacebookWebContext with the default application configuration was made, but no application configurations were found.", ex);
                    }
                }
                return (FacebookWebContext)FacebookWebSession.Current["__FBCONTEXT"];
            }
            set { FacebookWebSession.Current["__FBCONTEXT"] = value; }
        }

        public override FacebookWebSession Session 
        {
            get { return FacebookWebSession.Current; }
            protected internal set { FacebookWebSession.Current = value; }
        }

        public FacebookWebRequest Request { get { return FacebookWebRequest.Current; } }

        public String GetAuthorizationUrl(String next)
        {
            return String.Format("http://www.facebook.com/login.php?v={0}&api_key={1}&next={2}&canvas=", this.Version, this.ApiKey, String.IsNullOrEmpty(next) ? String.Empty : HttpUtility.UrlEncode(next));
        }
    }
}